package com.hostmanagement.user;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author glen
 * 
 */
public class AddUserServlet extends HttpServlet {

	private static final String INVALIDATE_USER_INFO = "invalide_user_info";
	private static final String USER_EXIST = "user_exist";

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		UserBean userBean = new UserBean();
		userBean.setUserName(req.getParameter("username"));
		userBean.setUserPassword(req.getParameter("userpassword"));
		userBean.setRuleId(Integer.valueOf(req.getParameter("ruleid")).intValue());
		userBean.setUserStatus(req.getParameter("userstatus"));
		userBean.setDogId(req.getParameter("dogid"));

		userBean.setDetailId(Integer.valueOf(req.getParameter("detailId")).intValue());
		userBean.setRealName(req.getParameter("realName"));
		userBean.setSex(req.getParameter("sex"));
		userBean.setBirthday(new Date(req.getParameter("birthday")));
		userBean.setAccontId(req.getParameter("accontId"));
		userBean.setPhone1(req.getParameter("phone1"));
		userBean.setPhone2(req.getParameter("phone2"));
		userBean.setMobile(req.getParameter("mobile"));
		userBean.setEmail(req.getParameter("email"));
		userBean.setAddress(req.getParameter("address"));
		userBean.setRemark(req.getParameter("remark"));
		
		if(!userBean.validateData()) {
			res.sendRedirect("index.jsp?errorCode=" + INVALIDATE_USER_INFO);
		}
		
		UserManage userManage = new UserManage();
		boolean isUserExist = false;
		try {
			isUserExist = userManage.isUserExist(userBean.getUserName());
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (isUserExist) {
			res.sendRedirect("index.jsp?errorCode=" + USER_EXIST);
		} else { // user is not existing
			try {
				userManage.addUser(userBean);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		res.sendRedirect("frame.jsp");

	}
}
